<template>
  <div>
    <form @submit.prevent="addFruit">
      <input type="text" v-model="fruit">
      <button>添加</button>
    </form>
    <ul>
      <li v-for="(item,index) in goodList" :key="index">
        {{item}}
        <button @click="modify(index)">编辑</button>
        <button @click="del(index)">删除</button>
      </li>
    </ul>
    <div class="wrap" :style="wrapStyle" v-show="isMt">
      <div class="mt">
        <form @submit.prevent="upData">
          <input type="text" v-model="modData">
          <br>
          <input type="submit">
          <input type="button" value="取消" @click="close">
        </form>
        
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data(){
    return{
      goodList:[],
      fruit:"",
      isMt:false,
      modData:"",
      selected:-1,
      wrapStyle:{
        height:""
      }
    }
  },
  mounted(){
    let height = document.documentElement.clientHeight;
    this.wrapStyle.height = height+"px";
  },
  created(){
    this.getFruitList(); // 初始化数据，还有其他初始化程序
  },
  methods:{
    // 获取数据
    getFruitList(){
      axios.get('http://127.0.0.1:3000/fruits').then(res=>{
        this.goodList = res.data;
      }).catch(err=>{
        console.log(err);
      })
    },
    // 添加数据
    addFruit(){
      axios.post('http://127.0.0.1:3000/fruits',{
        fruit:this.fruit
      }).then(()=>{
        this.getFruitList();
      })
    },
    del(index){
      axios.delete(`http://127.0.0.1:3000/fruits/${index}`).then(()=>{
        this.getFruitList();
      })
    },
    modify(index){
      this.selected = index;
      this.modData = this.goodList[index];
      this.close();
    },
    upData(){
      axios.put(`http://127.0.0.1:3000/fruits/${this.selected}`,{
        fruit:this.modData
      }).then(()=>{
        this.getFruitList();
        this.close();
      })
    },
    close(){
      this.isMt = !this.isMt;
    }
  }
}
</script>

<style>
  /* *{
    margin:0;
    padding:0;
    list-style: none;
    text-decoration: none;
  } */
  .wrap{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    background-color: rgba(30,30,30,0.5);
  }
  .mt{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width: 200px;
    height: 50px;
    background-color: #ccc;
    text-align: center;
    padding:30px 0;
  }
</style>
